﻿using System;
using System.IO;
using System.Web.UI;
using System.Drawing;
using System.Drawing.Imaging;
using System.Configuration;

namespace RN.ERP.Web.UserControl
{
    /// <summary>
    /// 图片上传、预览、剪裁
    /// </summary>
    public partial class ImgCutUpload : System.Web.UI.UserControl
    {
        #region 常量、属性

        /// <summary>
        /// 存放预览图的文件夹
        /// </summary>
        private const string PREVIEW_FOLDER_NAME = "../Download/preview";

        /// <summary>
        /// 登录的用户
        /// </summary>
        public string FileName
        {
            set
            {
                hidFileName.Value = value;
            }
            get
            {
                return hidFileName.Value;
            }
        }
        
        /// <summary>
        /// 系统编号 默认：EF
        /// </summary>
        public string SysCode
        {
            set
            {
                hidSysCode.Value = value;
            }
            get
            {
                return hidSysCode.Value;
            }
        }

        /// <summary>
        /// 功能编号 默认：Person
        /// </summary>
        public string FuncCode
        {
            set
            {
                hidFuncCode.Value = value;
            }
            get
            {
                return hidFuncCode.Value;
            }
        }

        /// <summary>
        /// 预览图最大宽度
        /// </summary>
        public string PreMaxWidth
        {
            set
            {
                hidPreMaxWidth.Value = value;
            }
            get
            {
                return hidPreMaxWidth.Value;
            }
        }

        /// <summary>
        /// 预览图最大高度
        /// </summary>
        public string PreMaxHeight
        {
            set
            {
                hidPreMaxHeight.Value = value;
            }
            get
            {
                return hidPreMaxHeight.Value;
            }
        }

        /// <summary>
        /// 剪裁预览图宽度
        /// </summary>
        public string ThumbWidth
        {
            set
            {
                hidThumbWidth.Value = value;
            }
            get
            {
                return hidThumbWidth.Value;
            }
        }

        /// <summary>
        /// 剪裁预览图高度
        /// </summary>
        public string ThumbHeight
        {
            set
            {
                hidThumbHeight.Value = value;
            }
            get
            {
                return hidThumbHeight.Value;
            }
        }

        /// <summary>
        /// 已上传图片宽度
        /// </summary>
        public string UploadedWidth
        {
            set
            {
                hidUploadedWidth.Value = value;
            }
            get
            {
                return hidUploadedWidth.Value;
            }
        }

        /// <summary>
        /// 已上传图片高度
        /// </summary>
        public string UploadedHeight
        {
            set
            {
                hidUploadedHeight.Value = value;
            }
            get
            {
                return hidUploadedHeight.Value;
            }
        }

        /// <summary>
        /// 剪裁图的高宽比率(height/width)
        /// </summary>
        public string AspectRatio
        {
            set
            {
                hidAspectRatio.Value = value;
            }
            get
            {
                return hidAspectRatio.Value;
            }
        }

        private int _maxSize = 0;
        /// <summary>
        /// 可上传的最大限制(单位：M 默认2M)
        /// 如果调用的页面没有指定MaxSize，则从Web.config获取
        /// </summary>
        public int MaxSize
        {
            set
            {
                _maxSize = value;
            }
            get
            {
                if (_maxSize == 0)
                {
                    string sizeStr = ConfigurationManager.AppSettings["ImgUploadMax"] ?? "2";
                    int.TryParse(sizeStr, out _maxSize);
                }
                return _maxSize;
            }
        }

        #endregion

        #region 图片处理操作

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                imgCurrent.ImageUrl = string.Format("../Handlers/GetFileHandler.ashx?gettype=last&fileName={0}.jpg&sysCode={1}&funcCode={2}&rand={3}", FileName, SysCode, FuncCode, Guid.NewGuid());
            }
        }

        /// <summary>
        /// 点击【上传预览图】
        /// </summary>
        protected void btnPreUpload_Click(object sender, EventArgs e)
        {
            if (fileUpload.PostedFile.ContentLength > MaxSize * 1024 * 1024)
            {
                Manager1.RadAlert(String.Format("请上传{0}M以内的图片。", MaxSize), 300, 150, "提示", "");
                return;
            }
            
            string fileName = this.fileUpload.PostedFile.FileName;
            int nLength = fileName.Length - fileName.LastIndexOf(".") - 1;
            string path = Server.MapPath(PREVIEW_FOLDER_NAME);

            ////这里的Guid将来要用UserGuid替换
            fileName = FileName + ".jpg";
            this.fileUpload.PostedFile.SaveAs(path + "/" + fileName);
            txturl.Text = PREVIEW_FOLDER_NAME + "/" + fileName;

            Image img = Bitmap.FromFile(path + "/" + fileName);
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "key1", "<script>Pic('" + PREVIEW_FOLDER_NAME + "/" + fileName + "'," + img.Width + "," + img.Height + ")</script>");
            img.Dispose();
        }

        /// <summary>
        /// 点击【保存】
        /// </summary>
        protected void btnImgSave_Click(object sender, EventArgs e)
        {
            int top, left, width, height;
            top = Convert.ToInt32(txttop.Text);
            left = Convert.ToInt32(txtleft.Text);
            width = Convert.ToInt32(txtwidth.Text);
            height = Convert.ToInt32(txtheight.Text);

            string file = txturl.Text.Trim();
            int nLength = file.Length - file.LastIndexOf(".") - 1;
            file = file.Substring(file.LastIndexOf(".") + 1, nLength);

            string sourceImg = Server.MapPath(txturl.Text.Trim());

            byte[] bs = CutImage(sourceImg, left, top, width, height);

            SaveImage(bs);

            imgCurrent.ImageUrl = string.Format("../Handlers/GetFileHandler.ashx?gettype=last&fileName={0}.jpg&sysCode={1}&funcCode={2}&rand ={3}", FileName, SysCode, FuncCode, Guid.NewGuid());
        }

        /// <summary>
        /// 裁剪图片
        /// </summary>
        /// <param name="sourceImg">原图片路径</param>
        /// <param name="desImg">裁剪图片路径</param>
        /// <param name="left">X</param>
        /// <param name="top">Y</param>
        /// <param name="width">宽</param>
        /// <param name="height">高</param>
        /// <returns>图片二进制</returns>
        public byte[] CutImage(string sourceImg, int left, int top, int width, int height)
        {
            Image img = Bitmap.FromFile(sourceImg);
            Image imgToSave = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(imgToSave);
            RectangleF sourceRect = new RectangleF(left, top, width, height);
            RectangleF destinationRect = new RectangleF(0, 0, width, height);
            MemoryStream ms = new MemoryStream();

            g.DrawImage(img, destinationRect, sourceRect, GraphicsUnit.Pixel);
            g.Save();
            
            imgToSave.Save(ms, ImageFormat.Jpeg);
            byte[] bs = ms.ToArray();

            ms.Close();
            g.Dispose();
            img.Dispose();
            imgToSave.Dispose();
            return bs;
        }

        /// <summary>
        /// 向文件服务器保存图片
        /// </summary>
        /// <param name="bs">二进制图片数据</param>
        public void SaveImage(byte[] bs)
        {
            if (bs == null)
            {
                Manager1.RadAlert("图片传输失败。", 300, 150, "提示", "");
                return;
            }
            string result = String.Empty;
            using (FileService.FileWebServiceSoapClient client = new FileService.FileWebServiceSoapClient())
            {
                try
                {
                    result = client.UploadImageBytes(bs, FileName + ".jpg", SysCode, FuncCode, true, "", "");
                    ////无返回值或返回值格式不对
                    if (String.IsNullOrEmpty(result) || result.Split(',').Length ==1 )
                    {
                        Manager1.RadAlert("上传失败。", 300, 150, "提示", "");
                    }
                    else
                    {
                        string[] results = result.Split(',');

                        ////操作成功时关闭当前窗口并刷新父页面
                        if (results[0] == "1")
                        {
                            Page.ClientScript.RegisterStartupScript(Page.GetType(), "closewin", "<script>returnToParent(0);</script>");
                        }
                        else
                        {
                            ////提示错误信息
                            Manager1.RadAlert(results[1], 300, 150, "提示", "returnToParent");
                        }
                    }
                }
                catch (Exception ex)
                {
                    hidLog.Value = String.Format("FileName:【{0}】,SysCode:【{1}】,FuncCode:【{2}】,Error:【{3}】"
                        ,FileName,SysCode,FuncCode,ex.Message);

                    Manager1.RadAlert("上传出现错误，请联系系统管理员。", 300, 150, "提示", "");
                }
            }
        }

        #endregion
    }
}
